require 'rest-client'   #to use RestClient
require 'json'          #to use JSON
require 'awesome_print' #to use ap helper

def getTotemAccessToken app, force=false
    uri = "https://mall.totembio.cn/api/gat?app=#{app}&code=#{ENV['PSI_PASSWORD']}#{force ? '&force=true' : ''}"
    res = RestClient.get uri
    JSON.parse(res.body)['data']['token']
end

#小程序
def getWeappAccessToken force=false
    return @pwat if @pwat
    @pwat = getTotemAccessToken 'weapp', force
end

#公众号
def getWechatAccessToken force=false
    return @twat if @twat
    @twat = getTotemAccessToken 'wechat', force
end

#企业微信
def getWeworkAccessToken force=false
    return @kwat if @kwat
    @kwat = getTotemAccessToken 'wework', force
end

def generateWeappUrlLink weapp_args
    res = wechatPost :generateWeappUrlLink, weapp_args
    ap res
    return res['url_link'] if res['url_link']
    return ''
end

def wechatPost api_name, data

    api = api_name.to_s
    base = 'https://api.weixin.qq.com/'
    base = 'https://qyapi.weixin.qq.com/' if api.include? 'Wework'
    wat = getWechatAccessToken true
    wat = getWeappAccessToken true if api.include? 'Weapp'
    wat = getWeworkAccessToken true if api.include? 'Wework'

    apiURLs={
        :sendTemplateMessage => "cgi-bin/message/template/send?access_token=#{wat}",
        :sendTextMessage => "cgi-bin/message/custom/send?access_token=#{wat}",
        :batchGet => "cgi-bin/user/info/batchget?access_token=#{wat}",
        :generateWeappUrlLink => "wxa/generate_urllink?access_token=#{wat}",
        :batchGetWeworkContactList => "cgi-bin/externalcontact/batch/get_by_user?access_token=#{wat}",
        :getWeworkCorpTagList => "cgi-bin/externalcontact/get_corp_tag_list?access_token=#{wat}",
        :getWeworkStrategyTagList => "cgi-bin/externalcontact/get_strategy_tag_list?access_token=#{wat}",
        :getWeworkGroupChatList => "cgi-bin/externalcontact/groupchat/list?access_token=#{wat}",
        :getWeworkGroupChatDetails =>"cgi-bin/externalcontact/groupchat/get?access_token=#{wat}",
        :remarkWeworkExternalContact =>"cgi-bin/externalcontact/remark?access_token=#{wat}",
        :markWeworkTag => "cgi-bin/externalcontact/mark_tag?access_token=#{wat}",
    }
    url = base + apiURLs[api_name]

    res = RestClient.post url, data.to_json
    return JSON.parse res.body
end

def sendSms phone='13600060044', template, data
    param = {   'api_key'=>ENV['PSI_PASSWORD'], 'template' => template, 'phone' => phone, 'data' => data }
    begin
        res = RestClient.post 'https://mall.totembio.cn/api/send_sms', param.to_json, :content_type => 'application/json'
    rescue=>e
        puts "ERROR: #{e.to_s}"
        return false
    end
    puts res.to_s
    return true
end

def sendDiscountSms phone = '13600060044', description = '订单确认收货后可评价，消费满1000元可享99折'
    #weapp_args = { "path" => "/pages/user/user", "query"=> "id=3&spreader_uid=736", "is_expire" => false }
    weapp_args = { "path" => "pages/order/list/index", "query"=> "status=3&spreader_uid=736&page=1&limit=5", "is_expire" => true }
    link = generateWeappUrlLink weapp_args
    data = {'admin_name' => '来自', 'order_id'=> " #{link} 点击链接，#{description}"
    }
    return sendSms phone, 'DELIVERY_CONFIRMED_NOTICE', data
end

def sendDiscountWtm openid = 'oqlyX6deLDP2EWlk0qZgWCU7wH6I', keyword1='订单确认收货后可评价', keyword2='消费满1000元可享99折'
    template_id = 'ePHoUsN_CvpBlOwQXsaG6nDqGWuktxirLTaBCJ5DPnI'
    page = "pages/order_list/index?status=3&page=1&limit=5"
    miniprogram = {appid: "wx1b441d1a37b278e1", pagepath:  page }
    url = 'https://mtx.totemlife.cn/'
    rec = {
        touser: openid, template_id: template_id, url: url, miniprogram: miniprogram,
        data: {
            first:  { value:  ""},                  #被微信弃用
            keyword1:  { value:  "#{keyword1}" },   #服务状态变更
            keyword2:  { value:  "#{keyword2}" },   #新功能开通
            remark: {value: ""} ,                   #被微信弃用
        },
    }
    res = wechatPost :sendTemplateMessage, rec
end

def sendDiscountNotice subscribe, phone, openid, discount

    names = { 99 => '铜牌', 98 => '银牌', 96 => '金牌', 93 => '钻石', 90 => '贵宾', 80 => '专家' }
    name = names[discount] || '其他'

    keyword1 = "订单确认收货后可评价"
    keyword2 = "消费满1000元可享99折"
    keyword2 = "当前可享#{name}会员#{discount}折" if discount < 100

    if subscribe == 0 
        sendDiscountSms phone.to_s, "#{keyword1}，#{keyword2}"
    else
        sendDiscountWtm openid.to_s, keyword1, keyword2
    end
end
#sendDiscountNotice 1, '13600060044', 'oqlyX6deLDP2EWlk0qZgWCU7wH6I', 99
#sendDiscountNotice 0, '13600060044', 'oqlyX6deLDP2EWlk0qZgWCU7wH6I', 60
